<template>
  <el-card class="card">
    <div slot="header">
      <span>添加账号</span>
    </div>
    <el-form
      ref="formRef"
      :rules="rules"
      size="small"
      label-width="80px"
      class="form"
      :model="formData"
    >
      <el-form-item label="账号" prop="account">
        <el-input v-model="formData.account"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="formData.password"></el-input>
      </el-form-item>
      <el-form-item label="用户组" prop="userGroup">
        <el-select placeholder="请选择用户组" v-model="formData.userGroup">
          <el-option value="超级管理员" label="超级管理员"></el-option>
          <el-option value="普通用户" label="普通用户"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="password">
        <el-button @click="submit" type="primary">添加</el-button>
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
// 解构添加账号接口
import { addUserReq } from "@/api/user";

// 定义账号验证函数
const YanzhengIstrue = (rule, value, callback) => {
  if (!value) {
    callback(new Error("账号不能为空"));
  } else if (!/^[a-z]{6,12}$/.test(value)) {
    callback(new Error("账号必须是6-12位的英文字母"));
  } else {
    callback();
  }
};
// 定义密码验证函数
const passwordIstrue = (rule, value, callback) => {
  if (!value) {
    callback(new Error("密码不能为空"));
  } else if (!/^[0-9]{6,18}$/.test(value)) {
    callback(new Error("密码必须是6-18位的纯数字"));
  } else {
    callback();
  }
};
export default {
  data() {
    return {
      formData: {
        account: "",
        password: "",
        userGroup: "",
      },
      // 验证规则
      rules: {
        account: [{ validator: YanzhengIstrue, trigger: "blur" }],
        password: [{ validator: passwordIstrue, trigger: "blur" }],
        userGroup: [{ required: true, message: "请选择用户组" }],
      },
    };
  },

  // 方法
  methods: {
    // 提交表单
    submit() {
      this.$refs.formRef.validate(async (valid) => {
        if (valid) {
          // 发送请求
          let res = await addUserReq(this.formData);
          // 解构数据
          let { code, msg } = res.data;
          // 判断
          if (code === 0) {
            // 跳转
            this.$router.push('/account/account-list');
          }
        }

        // console.log('valid',valid);
      });
    },
    reset() {
      this.$refs.formRef.resetFields();
    },
  },
};
</script>

<style lang="scss" scoped>
.form {
  width: 285px;
}
</style>